/**
 * 通知模块 - 统一管理通知相关功能
 * 包含通知加载、渲染、标记已读、统计等功能
 */

// ==================== 通知数据管理 ====================

/**
 * 加载通知数据
 * @param {Object} options - 配置选项
 * @param {string} options.containerId - 容器元素ID
 * @param {string} options.loadingId - 加载状态元素ID
 * @param {string} options.noNotificationsId - 无通知提示元素ID
 * @param {Function} options.onSuccess - 成功回调
 * @param {Function} options.onError - 错误回调
 */
function loadNotifications(options = {}) {
    console.log('loadNotifications 开始执行', options);
    
    const {
        containerId = 'notifications-list',
        loadingId = 'loading',
        noNotificationsId = 'no-notifications',
        onSuccess = null,
        onError = null
    } = options;

    const container = document.getElementById(containerId);
    const loading = document.getElementById(loadingId);
    const noNotifications = document.getElementById(noNotificationsId);
    
    console.log('DOM元素检查:', {
        container: !!container,
        loading: !!loading,
        noNotifications: !!noNotifications
    });
    
    if (!container) {
        console.warn('通知容器未找到:', containerId);
        if (onError) onError(new Error(`容器未找到: ${containerId}`));
        return;
    }
    
    // 显示加载状态
    if (loading) loading.style.display = 'block';
    if (noNotifications) noNotifications.style.display = 'none';
    container.innerHTML = '';
    
    console.log('开始API调用: /api/notifications');
    
    fetch('/api/notifications')
        .then(response => {
            console.log('API响应状态:', response.status, response.statusText);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('API数据接收成功:', data);
            if (loading) loading.style.display = 'none';
            
            if (Array.isArray(data) && data.length > 0) {
                console.log('开始渲染通知列表');
                renderNotifications(data, { containerId });
                updateNotificationStats(data);
                
                if (onSuccess) onSuccess(data);
            } else {
                console.log('没有通知数据');
                if (noNotifications) noNotifications.style.display = 'block';
            }
        })
        .catch(error => {
            console.error('加载通知数据错误:', error);
            if (loading) loading.style.display = 'none';
            if (noNotifications) noNotifications.style.display = 'block';
            
            // 显示错误信息
            if (container) {
                container.innerHTML = '<div class="error-message">加载通知失败，请刷新页面重试</div>';
            }
            
            if (onError) onError(error);
        });
}

// ==================== 通知渲染 ====================

/**
 * 渲染通知列表
 * @param {Array} notifications - 通知数据数组
 * @param {Object} options - 配置选项
 * @param {string} options.containerId - 容器元素ID
 * @param {boolean} options.enableCampusBadge - 是否启用校园网标签
 * @param {boolean} options.enableClickEvents - 是否启用点击事件
 */
function renderNotifications(notifications, options = {}) {
    console.log('renderNotifications 开始执行', { notificationsCount: notifications.length, options });
    
    const {
        containerId = 'notifications-list',
        enableCampusBadge = true,
        enableClickEvents = true
    } = options;

    const container = document.getElementById(containerId);
    if (!container) {
        console.error('渲染容器未找到:', containerId);
        return;
    }
    
    container.innerHTML = '';
    
    notifications.forEach((notification, index) => {
        try {
            const item = createNotificationItem(notification, { enableCampusBadge });
            container.appendChild(item);
            
            if (enableClickEvents) {
                addNotificationClickEvent(item, notification);
            }
        } catch (error) {
            console.error(`渲染通知 ${index} 失败:`, error, notification);
        }
    });
    
    console.log('通知渲染完成');
}

/**
 * 创建通知项目元素
 * @param {Object} notification - 通知数据
 * @param {Object} options - 配置选项
 * @param {boolean} options.enableCampusBadge - 是否启用校园网标签
 * @returns {HTMLElement} 通知项目元素
 */
function createNotificationItem(notification, options = {}) {
    const { enableCampusBadge = true } = options;
    
    const item = document.createElement('div');
    item.className = 'notification-item';
    if (!notification.is_read) {
        item.classList.add('unread');
    }
    item.dataset.category = notification.category;
    item.dataset.id = notification.id;
    item.dataset.url = notification.url || '';
    
    const date = formatDate(notification.publish_date);
    
    const campusBadge = enableCampusBadge && notification.campus_network_only ? 
        '<div class="campus-network-badge">校园网访问</div>' : '';
    
    item.innerHTML = `
        ${campusBadge}
        <div class="notification-title">${notification.title}</div>
        <div class="notification-date">发布日期: ${date}</div>
        <div class="notification-summary">${notification.content}</div>
    `;
    
    return item;
}

/**
 * 为通知项目添加点击事件
 * @param {HTMLElement} item - 通知项目元素
 * @param {Object} notification - 通知数据
 */
function addNotificationClickEvent(item, notification) {
    item.addEventListener('click', function() {
        // 标记为已读
        markNotificationAsRead(notification.id).then(() => {
            if (item.classList.contains('unread')) {
                item.classList.remove('unread');
                updateNotificationStats();
            }
        }).catch(err => {
            console.error('标记通知已读失败:', err);
        });

        // 打开URL（如存在）
        const url = notification.url;
        if (url && /^https?:\/\//i.test(url)) {
            window.open(url, '_blank');
        }
    });
}

// ==================== 通知操作 ====================

/**
 * 标记通知为已读
 * @param {number} notificationId - 通知ID
 * @returns {Promise} 操作结果
 */
function markNotificationAsRead(notificationId) {
    return fetch('/api/notifications/mark-read', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: parseInt(notificationId) })
    }).then(res => res.json()).then(data => {
        if (data && data.success) {
            console.log('通知已标记为已读:', notificationId);
            return data;
        } else {
            throw new Error('标记通知已读失败');
        }
    });
}

/**
 * 标记所有通知为已读
 * @returns {Promise} 操作结果
 */
function markAllNotificationsAsRead() {
    return fetch('/api/notifications/mark-all-read', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    }).then(res => res.json()).then(data => {
        if (data && data.success) {
            // 更新UI状态
            const unreadItems = document.querySelectorAll('.notification-item.unread');
            unreadItems.forEach(item => item.classList.remove('unread'));
            updateNotificationStats();
            console.log('所有通知已标记为已读');
            return data;
        } else {
            throw new Error('标记所有通知已读失败');
        }
    });
}

// ==================== 通知统计 ====================

/**
 * 更新通知统计信息
 * @param {Array} notifications - 通知数据数组（可选）
 */
function updateNotificationStats(notifications = null) {
    const totalElement = document.getElementById('totalNotifications');
    const unreadElement = document.getElementById('unreadNotifications');
    
    if (!totalElement || !unreadElement) {
        console.warn('统计元素未找到');
        return;
    }
    
    if (notifications) {
        const total = notifications.length;
        const unread = notifications.filter(n => !n.is_read).length;
        
        totalElement.textContent = total;
        unreadElement.textContent = unread;
    } else {
        // 从DOM中计算
        const items = document.querySelectorAll('.notification-item');
        const unreadItems = document.querySelectorAll('.notification-item.unread');
        
        totalElement.textContent = items.length;
        unreadElement.textContent = unreadItems.length;
    }
}

/**
 * 更新通知计数（简化版本，用于base.js兼容）
 */
function updateNotificationCount() {
    updateNotificationStats();
}

// ==================== 工具函数 ====================

/**
 * 格式化日期
 * @param {string} dateString - 日期字符串
 * @returns {string} 格式化后的日期
 */
function formatDate(dateString) {
    try {
        const date = new Date(dateString);
        const now = new Date();
        const diffTime = Math.abs(now - date);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        if (diffDays === 1) {
            return '昨天';
        } else if (diffDays === 0) {
            return '今天';
        } else if (diffDays < 7) {
            return `${diffDays}天前`;
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    } catch (error) {
        console.error('日期格式化失败:', error, dateString);
        return dateString;
    }
}

// ==================== 页面初始化 ====================

// 防重复初始化标记
let isNotificationPageInitialized = false;

/**
 * 初始化通知页面
 */
function initNotificationsPage() {
    // 防重复初始化
    if (isNotificationPageInitialized) {
        console.log('通知页面已初始化，跳过重复初始化');
        return;
    }
    
    console.log('initNotificationsPage 开始执行');
    isNotificationPageInitialized = true;
    
    // 绑定全部标记为已读按钮
    const markAllReadBtn = document.getElementById('markAllRead');
    if (markAllReadBtn) {
        markAllReadBtn.addEventListener('click', markAllNotificationsAsRead);
        console.log('全部标记为已读按钮已绑定');
    } else {
        console.warn('全部标记为已读按钮未找到');
    }
    
    // 加载通知数据
    loadNotifications();
}

// ==================== 导出模块 ====================

// 如果支持ES6模块，则导出函数
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        loadNotifications,
        renderNotifications,
        createNotificationItem,
        markNotificationAsRead,
        markAllNotificationsAsRead,
        updateNotificationStats,
        updateNotificationCount,
        formatDate,
        initNotificationsPage
    };
}
